package com.vegetable.modules.oauth2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

@Slf4j
public class ChinaUMSAuth {
    private String appId;
    private String appKey;
    private String tokenUrl;

    // 构造函数
    public ChinaUMSAuth(String appId, String appKey, boolean isProduction) {
        this.appId = appId;
        this.appKey = appKey;

        if (isProduction) {
            this.tokenUrl = "https://api-mop.chinaums.com/v2/token/access";
        } else {
            this.tokenUrl = "https://test-api-open.chinaums.com/v2/token/access";
        }
    }

    // 生成SHA256签名
    private String generateSHA256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();

            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("SHA256加密失败", e);
        }
    }

    // 获取AccessToken
    public JSONObject getAccessToken() {
        // 生成时间戳 (格式: yyyyMMddHHmmss)
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        // 生成随机数
        String nonce = UUID.randomUUID().toString().replace("-", "");

        // 生成签名: SHA256_hex(appId+timestamp+nonce+appKey)
        String signContent = appId + timestamp + nonce + appKey;
        String signature = generateSHA256(signContent);

        // 构建请求JSON
        JSONObject requestData = new JSONObject();
        requestData.put("appId", appId);
        requestData.put("timestamp", timestamp);
        requestData.put("nonce", nonce);
        requestData.put("signMethod", "SHA256");
        requestData.put("signature", signature);

        try {
            // 创建HTTP连接
            URL url = new URL(tokenUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            // 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestData.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }

                    JSONObject result = new JSONObject(response.toString());
                    return result;
                }
            } else {
                JSONObject error = new JSONObject();
                error.put("errCode", "HTTP_" + responseCode);
                error.put("errInfo", "HTTP请求失败，状态码: " + responseCode);
                return error;
            }
        } catch (Exception e) {
            JSONObject error = new JSONObject();
            error.put("errCode", "EXCEPTION");
            error.put("errInfo", "请求异常: " + e.getMessage());
            return error;
        }
    }

    // 使用示例
    public static void main(String[] args) {
        // 您的认证信息
        String appId = "10037e6f68e462980169043abe98002a";
        String appKey = "fb5d5fe2594446ce8a914f878b28b0ad";

        // 创建认证对象 (使用测试环境)
        ChinaUMSAuth auth = new ChinaUMSAuth(appId, appKey, false);

        // 获取AccessToken
        JSONObject result = auth.getAccessToken();

        if ("0000".equals(result.optString("errCode"))) {
            log.info("获取AccessToken成功!");
            log.info("AccessToken: " + result.optString("accessToken"));
            log.info("有效期: " + result.optString("expiresIn") + "秒");

            // 在实际应用中，您应该保存这个token并在后续请求中使用
            // 注意：token有效期为1小时，不要频繁获取
        } else {
            log.info("获取AccessToken失败!");
            log.info("错误代码: " + result.optString("errCode"));
            log.info("错误信息: " + result.optString("errInfo"));
        }
    }
}